package com.situ.mall.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.mall.admin.pojo.dto.AdminLoginDTO;
import com.situ.mall.admin.pojo.dto.AdminPasswordDTO;
import com.situ.mall.admin.service.IAdminService;
import com.situ.mall.common.util.CommonUtil;
import com.situ.mall.common.util.JwtUtil;
import com.situ.mall.common.util.Result;
import com.situ.mall.common.util.ThreadLocalUtil;
import com.situ.mall.pojo.entity.admin.Admin;
import com.situ.mall.admin.pojo.query.AdminQuery;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author CKX
 * @since 2024-10-09
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IAdminService adminService;

    @GetMapping("/list")
    public Result list(AdminQuery adminQuery) {
        IPage<Admin> adminIPage = new Page<>(adminQuery.getPage(), adminQuery.getLimit());
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(adminQuery.getName()), "name", adminQuery.getName());
        queryWrapper.like(!ObjectUtils.isEmpty(adminQuery.getPhone()), "phone", adminQuery.getPhone());
        queryWrapper.between(!ObjectUtils.isEmpty(adminQuery.getBeginCreateTime()) && !ObjectUtils.isEmpty(adminQuery.getEndCreateTime()),
                "create_time", adminQuery.getBeginCreateTime(), adminQuery.getEndCreateTime());
        adminService.page(adminIPage, queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("total", adminIPage.getTotal());
        map.put("list", adminIPage.getRecords());
        return Result.ok(map);
    }

    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        adminService.removeById(id);
        return Result.ok("删除成功");
    }

    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids) {
        adminService.removeByIds(Arrays.asList(ids));
        return Result.ok("删除成功");
    }

    @PostMapping("/add")
    public Result add(@RequestBody Admin admin) {
        adminService.save(admin);
        return Result.ok("添加成功");
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Admin admin = adminService.getById(id);
        return Result.ok(admin);
    }

    @PutMapping("/update")
    public Result update(@RequestBody Admin admin) {
        adminService.saveOrUpdate(admin);
        return Result.ok("更新成功");
    }

    @PostMapping("/login")
    public Result login(@RequestBody AdminLoginDTO adminLoginDTO, HttpServletRequest request) {
        //先判断验证码是否正确
        String captcha = (String) redisTemplate.opsForValue().get(CommonUtil.getCaptchaKey(request));
        if (StringUtils.isEmpty(captcha)) {
            return Result.error("验证码已失效");
        }
        if (!captcha.equalsIgnoreCase(adminLoginDTO.getCaptcha())) {
            return Result.error("验证码错误");
        }
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", adminLoginDTO.getName());
        //根据用户名查询
        Admin loginAdmin = adminService.getOne(queryWrapper);
        //判断用户名是否存在
        if (loginAdmin == null) {
            return Result.error("用户名错误");
        }
        //判断密码是否正确
        if (!adminLoginDTO.getPassword().equalsIgnoreCase(loginAdmin.getPassword())) {
            return Result.error("密码错误");
        }
        //判断用户是否被禁用
        if (loginAdmin.getStatus() == 0) {
            return Result.error("用户已被禁用");
        }

        //登录成功
        Map<String, Object> map = new HashMap<>();
        map.put("id", loginAdmin.getId());
        map.put("name", loginAdmin.getName());
        String token = JwtUtil.createToken(map);
        return Result.ok("登录成功", token);
    }

    @GetMapping("/adminInfo")
    public Result adminInfo(@RequestHeader(name = "Authorization") String token) {
        Map<String, Object> map = JwtUtil.parseToken(token);
        String name = (String) map.get("name");
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        Admin admin = adminService.getOne(queryWrapper);
        return Result.ok(admin);
    }

    @PutMapping("/updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Integer id, @PathVariable Integer status) {
        UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("status", status);
        adminService.update(updateWrapper);
        return Result.ok("更新成功");
    }

    @RequestMapping("/resetPassword")
    public Result resetPassword(@RequestBody AdminPasswordDTO adminPasswordDTO) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("password", adminPasswordDTO.getOldPassword());
        queryWrapper.eq("id", id);
        Admin admin = adminService.getOne(queryWrapper);
        if (admin == null) {
            return Result.error("原密码错误");
        }

        UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", admin.getId()).set("password", adminPasswordDTO.getNewPassword());
        adminService.update(updateWrapper);
        return Result.ok("更新成功");
    }

    @RequestMapping("/forgotPassword")
    public Result forgotPassword(@RequestBody AdminPasswordDTO adminPasswordDTO) {
        Admin admin = adminService.selectByPhone(adminPasswordDTO);
        if (admin == null) {
            return Result.error("该手机号未有创建用户");
        }

        UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", admin.getId()).set("password", adminPasswordDTO.getNewPassword());
        adminService.update(updateWrapper);
        return Result.ok("更新成功");
    }
}

